package com.server.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.service.IMngBaseService;

@Service("MngBaseService")
public class MngBaseService implements IMngBaseService{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	

	@Override
	public List<Map<String, Object>> getMenu(String adminUser) {
		List<Map<String, Object>> menus = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> menuList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> tempList = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> tempListSub = new ArrayList<Map<String,Object>>();
		String sqlRoleId = "select * from education.admin_user where nickname='%s'";
		List <Map<String,Object>> listRole = jdbcTemplate.queryForList(String.format(sqlRoleId, adminUser));
		if(listRole.size() <= 0 ){
			return menuList;
		}
		Map<String, Object> roleMap = listRole.get(0);
		int id = (int) roleMap.get("role_id");
		String sql = "select * from education.admin_role where id='%d'";
		List <Map<String,Object>> list = jdbcTemplate.queryForList(String.format(sql, id));
		if (list.size() <= 0) {
			return menuList;
		}
		Map<String, Object> map = list.get(0);
		String auth = map.get("authority").toString();
		if(!StringUtils.isEmpty(auth) && auth.equalsIgnoreCase("all")){
			String sql1 = "select * from education.admin_menu where valid=1 order by sort asc";
			menus= jdbcTemplate.queryForList(sql1);
		}else{
			String sql2 = "select * from education.admin_menu where (id in (%s) or p_id = 0) and valid=1 order by sort asc";
			menus = jdbcTemplate.queryForList(String.format(sql2, auth));
		}
		
		for(Map<String, Object> menusArrTem: menus){
			int p_id = (int) menusArrTem.get("p_id");
			if(p_id==0){
				tempList.add(menusArrTem);
			}
		}
		
		if(tempList.size()>0){
			for (int i = 0; i < tempList.size(); i++) {
				Map<String, Object> tempMap = new HashMap<String, Object>();
				Map<String, Object> menuMap = tempList.get(i);
				List<Map<String, Object>> subTempList = new ArrayList<Map<String,Object>>();
				for (int j = 0; j < menus.size(); j++) {
					Map<String, Object> subMap = menus.get(j);
					if(menuMap.get("id")==subMap.get("p_id")){
						tempMap = menuMap;
						subTempList.add(subMap);
						tempMap.put("menu_sub", subTempList);
					}
				}
				if(!tempMap.isEmpty()){
					menuList.add(tempMap);
				}
			}
		}
		return menuList;
	}

}


